from selenium import webdriver
import pickle
import time
import os

# 淘宝首页 URL
TAOBAO_URL = "https://www.taobao.com"
# Cookie 保存路径
COOKIE_FILE = "taobao_cookies.pkl"


def init_browser():
    """初始化 Chrome 浏览器驱动（手动指定驱动路径，需提前下载对应版本的 chromedriver）"""
    driver = webdriver.Chrome(executable_path=r"D:\python\chromedriver.exe")  # 替换为你的 chromedriver 实际路径
    driver.maximize_window()
    driver.get(TAOBAO_URL)
    return driver


def save_cookies(driver):
    """保存当前会话的 Cookie 到本地文件"""
    cookies = driver.get_cookies()
    with open(COOKIE_FILE, "wb") as f:
        pickle.dump(cookies, f)
    print(f"Cookie 已保存到 {COOKIE_FILE}")


def load_cookies(driver):
    """从本地文件加载 Cookie 到浏览器会话"""
    if not os.path.exists(COOKIE_FILE):
        print("未找到 Cookie 文件，请先手动登录")
        return False
    try:
        with open(COOKIE_FILE, "rb") as f:
            cookies = pickle.load(f)
        for cookie in cookies:
            if "expiry" in cookie:
                del cookie["expiry"]
            driver.add_cookie(cookie)
        print("Cookie 加载成功，刷新页面使 Cookie 生效...")
        driver.refresh()
        return True
    except Exception as e:
        print(f"加载 Cookie 失败：{e}")
        return False


def check_login_status(driver):
    """检查是否已成功登录淘宝"""
    try:
        # 定位登录后的用户名区域（淘宝首页登录后特有的元素）
        driver.find_element_by_css_selector(".site-nav-user a")
        print("已成功登录淘宝")
        return True
    except:
        print("未登录或登录状态失效")
        return False


def manual_login(driver):
    """手动登录流程（需用户在浏览器中完成登录操作）"""
    print("请在浏览器中手动登录淘宝（30秒内完成）...")
    time.sleep(30)
    driver.refresh()
    if check_login_status(driver):
        save_cookies(driver)
    else:
        print("登录失败，请重新尝试")


def main():
    driver = init_browser()
    try:
        if not load_cookies(driver):
            manual_login(driver)

        if check_login_status(driver):
            print("开始执行登录后的操作...")
            time.sleep(5)
            # 示例：搜索商品
            search_box = driver.find_element_by_id("q")
            search_box.send_keys("手机")
            search_box.submit()
            time.sleep(5)
    finally:
        driver.quit()
        print("浏览器已关闭")


if __name__ == "__main__":
    main()